/* ---------------------------------------------------------------------------------------------
 *
 *            Capital Alliance Software Confidential Proprietary
 *            (c) Copyright CAS 201{x}, All Rights Reserved
 *                          www.pekall.com
 *
 * ----------------------------------------------------------------------------------------------
 */

package com.android.music.service;

import java.io.IOException;
import java.util.List;
import java.util.Random;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Binder;
import android.os.IBinder;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.android.music.HomeActivity;
import com.android.music.MusicApplication;
import com.android.music.R;
import com.android.music.database.SQLHelper;
import com.android.music.model.Music;
import com.android.music.model.MusicPositionInfo;
import com.android.music.util.DeskLrcoperate;
import com.android.music.util.SharedPreference;
import com.android.music.util.Util;

/**
 * Music service 控制 music 播放
 * 
 * @author LeiKang
 */
public class MusicService extends Service implements Runnable {

    /**
     * sdcard中music列表
     */
    private List<Music> mListMusic;

    private Music playingMusic;

    /**
     * 当前播放信息
     */
    private MusicPositionInfo mMusicInfo;

    /**
     * MediaPlayer class can be used to control playback of audio/video files
     * and streams
     */
    private MediaPlayer mMediaPlayer;

    /**
     * 播放完成监听
     */
    private OnCompletionListener mediaCompletionListner;

    /**
     * share设置
     */
    private SharedPreference mSharedPreference;

    /**
     * 初始播放位置
     */
    private int mPlayMusicId;

    /**
     * 播放模式
     */
    private String playModel;

    private DeskLrcoperate mDeskLrcoperate;

    // private MusicApplication mMusicApplication;

    private Thread mThread;

    private NotificationManager mNotificationManager;

    private Notification notification;

    private PendingIntent contentIntent;

    private Intent openintent;

    private Context mContext;

    private Boolean threadable;

    private Intent intentMusicChangeBroadcast;

    private Intent intentMusicPositionBroadcast;

    @Override
    public void onCreate() {
        super.onCreate();
        threadable = true;
        mContext = this;
        mSharedPreference = new SharedPreference(this);
        mListMusic = MusicApplication.getInstance().getListMusic();

        if (mListMusic.size() != 0)
            init();
    }

    private void init() {

        mMusicInfo = new MusicPositionInfo();
        mMediaPlayer = new MediaPlayer();
        mDeskLrcoperate = new DeskLrcoperate(this);
        mMediaPlayer.reset();
        mMediaPlayer.setOnCompletionListener(mediaCompletionListner);
        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notification = new Notification(R.drawable.stat_notify_musicplayer,
                getString(R.string.app_name), System.currentTimeMillis());
        notification.flags = notification.flags | Notification.FLAG_ONGOING_EVENT;
        openintent = new Intent(mContext, HomeActivity.class);
        contentIntent = PendingIntent.getActivity(mContext, 0, openintent, 0);

        notification.tickerText = getString(R.string.app_name);
        notification.setLatestEventInfo(this, getString(R.string.app_name), "", contentIntent);
        mNotificationManager.notify(0, notification);
        try {
            mPlayMusicId = mSharedPreference.getInt(Util.LAST_PLAY_MUSIC, 0);
            mMediaPlayer.setDataSource(mListMusic.get(mPlayMusicId).path);
            mMediaPlayer.prepare();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        mediaCompletionListner = new OnCompletionListener() {
            public void onCompletion(MediaPlayer mp) {
                /** 根据播放模式进行歌曲选择 */
                playModel = mSharedPreference.getString(Util.TAG_PLAY_MODEL, Util.PLAY_MODEL_ALL);
                if (playModel.equals(Util.PLAY_MODEL_ALL)) {
                    next();
                } else if (playModel.equals(Util.PLAY_MODEL_SINGLE)) {
                    mediaPrepare();
                } else if (playModel.equals(Util.PLAY_MODEL_RANDOM)) {
                    Random rand = new Random();
                    mPlayMusicId = rand.nextInt(mListMusic.size());
                    mediaPrepare();
                }
                musicChangeBroadCast();
            }
        };
        mThread = new Thread(this);
        mThread.start();

        intentMusicChangeBroadcast = new Intent(Util.MUSIC_CHANGE_BROADCAST);
        intentMusicPositionBroadcast = new Intent(Util.MUSIC_POSITION_BROADCAST);
    }

    /**
     * 用于歌曲的切换 上一首，下一首，单曲循环
     * 
     * @author leikang
     */
    private void mediaPrepare() {
        try {
            if (mMediaPlayer == null)
                mMediaPlayer = new MediaPlayer();
            mMediaPlayer.reset();
            mMediaPlayer.setOnCompletionListener(mediaCompletionListner);
            mMediaPlayer.setDataSource(mListMusic.get(mPlayMusicId).path);
            mMediaPlayer.prepare();
            mMusicInfo.position = 0;
            mMediaPlayer.start();
        } catch (IllegalArgumentException e1) {
            e1.printStackTrace();
        } catch (IllegalStateException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
    }

    private void previous() {
        if (mPlayMusicId == 0) {
            mPlayMusicId = mListMusic.size() - 1;
        } else {
            mPlayMusicId--;
        }
        mediaPrepare();
        musicChangeBroadCast();
    }

    private void next() {
        if (mPlayMusicId == mListMusic.size() - 1) {
            mPlayMusicId = 0;
        } else {
            mPlayMusicId++;
        }
        mediaPrepare();
        musicChangeBroadCast();
    }

    public void inite() {
        if (mMediaPlayer == null)
            mMediaPlayer = new MediaPlayer();
        if (mMediaPlayer.isPlaying()) {
            mMediaPlayer.pause();
            MusicApplication.getInstance().setIsPlaying(false);
        } else {
            if (mMusicInfo.position == 0)
                musicChangeBroadCast();
            mMediaPlayer.seekTo(mMusicInfo.position);
            mMediaPlayer.start();
            MusicApplication.getInstance().setIsPlaying(true);
        }
    }

    public String getDateByPosition(List<Music> c, int position) {
        return c.get(position).path;
    }

    public void onDestroy() {
        super.onDestroy();
        threadable = false;
    }

    public MusicPositionInfo getMusicPlayingInfo() {
        return mMusicInfo;
    }

    /* ========================== 绑定service ====================== */
    private ServiceBinder serviceBinder = new ServiceBinder();

    public class ServiceBinder extends Binder implements IPlayService {
        public MusicPositionInfo getMusicPlayingInfo() {
            if (!threadable)
                return mMusicInfo;
            mMusicInfo.id = mPlayMusicId;
            if (mMediaPlayer.isPlaying())
                mMusicInfo.position = mMediaPlayer.getCurrentPosition();
            return mMusicInfo;
        }

        public void nextSong() {
            next();
        }

        public void playingOrPause() {
            inite();
        }

        public void preSong() {
            previous();
        }

        public void setPosition(int position) {
            mMusicInfo.position = position;
            mMediaPlayer.seekTo(mMusicInfo.position);
            if (mMediaPlayer.isPlaying())
                mMediaPlayer.start();
        }

        public void itemClickPlay(int musicId) {
            mPlayMusicId = musicId;
            mediaPrepare();
            musicChangeBroadCast();
        }

        public void stopMedia() {

            dismissDesktop();
            threadable = false;
            mNotificationManager.cancel(0);
            // mMediaPlayer.reset();
            // mMediaPlayer.stop();
            mMediaPlayer.release();
            // MusicApplication.getInstance().initLrc(playingMusic.title);
            mSharedPreference.saveInt(Util.LAST_PLAY_MUSIC, mPlayMusicId);
            mSharedPreference.saveInt(Util.IS_FIRST_LOAD, 0);

        }

        public void showDeskTopLrc() {
            // contentIntent = PendingIntent.getActivity(mContext, 0,
            // openintent, 0);
            if (threadable)
                showDesktop();
        }

        public void closeDeskTopLrc() {
            // contentIntent = null;
            dismissDesktop();
        }

        public void playByPath(String path) {
            try {
                mMediaPlayer.reset();
                mMediaPlayer.setOnCompletionListener(mediaCompletionListner);
                mMediaPlayer.setDataSource(path);
                mMediaPlayer.prepare();
                mMusicInfo.position = 0;
                mMediaPlayer.start();
            } catch (IllegalArgumentException e1) {
                e1.printStackTrace();
            } catch (IllegalStateException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            musicChangeBroadCast();
        }

    }

    public IBinder onBind(Intent intent) {
        return serviceBinder;
    }

    /* ===================== 切换歌曲时 发送广播 ========================= */
    private void musicChangeBroadCast() {
        // Toast.makeText(mContext, "切换歌曲", Toast.LENGTH_SHORT).show();
        playingMusic = mListMusic.get(mPlayMusicId);
        MusicApplication.getInstance().setLrcMap(playingMusic);
        MusicApplication.getInstance().setPlayingMusic(playingMusic);
        mDeskLrcoperate.initLrcMap();
        sendBroadcast(intentMusicChangeBroadcast);
        setNotification();
        ContentValues values = new ContentValues();
        values.put("_path", playingMusic.path);
        values.put("_duration", playingMusic.duration);
        values.put("_description", playingMusic.album);

        Cursor cursor = mContext.getContentResolver().query(SQLHelper.CONTENT_URI_HISTORY, null,
                "_path = ?", new String[] {
                    playingMusic.path
                }, null);
        if (cursor.getCount() == 0)
            mContext.getContentResolver().insert(SQLHelper.CONTENT_URI_HISTORY, values);
    }

    /* ===================== 时时发送播放信息 广播 ========================= */
    private void musicPositionBroadCast() {
        if (threadable) {
            if (mMediaPlayer.isPlaying()) {
                mMusicInfo.position = mMediaPlayer.getCurrentPosition();
                intentMusicPositionBroadcast.putExtra("music_position", mMusicInfo.position);
                sendBroadcast(intentMusicPositionBroadcast);
            }
        }
    }

    /* ====================== 桌面迷你歌词 ======================= */

    private boolean isShowDeskTop = false;

    private void showDesktop() {
        if (mDeskLrcoperate != null) {
            mDeskLrcoperate.show();
            isShowDeskTop = true;
        }
    }

    private void dismissDesktop() {
        if (!isShowDeskTop)
            return;
        mDeskLrcoperate.dismiss();
        isShowDeskTop = false;
    }

    public void run() {
        while (threadable) {
            try {
                Thread.sleep(100);
                if (threadable && mMediaPlayer.isPlaying()) {
                    mMusicInfo.position = mMediaPlayer.getCurrentPosition();
                    mDeskLrcoperate.changeMessage(mMusicInfo.position);
                    musicPositionBroadCast();
                }
            } catch (InterruptedException e) {
            }

        }
    }

    /* ====================== Notifacation ============================ */

    private void setNotification() {
        notification.tickerText = mListMusic.get(mPlayMusicId).title;
        notification.setLatestEventInfo(this, getString(R.string.app_name),
                getString(R.string.is_playing) + mListMusic.get(mPlayMusicId).title, contentIntent);
        mNotificationManager.notify(0, notification);
    }

    /* ======================来电处理 =================================== */
    class PhoneStatReceiver extends BroadcastReceiver {

        private static final String TAG = "PhoneStatReceiver";

        // private static MyPhoneStateListener phoneListener = new
        // MyPhoneStateListener();

        private boolean incomingFlag = false;

        private String incoming_number = null;

        public void onReceive(Context context, Intent intent) {
            // 如果是拨打电话
            if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
                incomingFlag = false;
                String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
                Log.i(TAG, "call OUT: " + phoneNumber);
            } else {
                // 如果是来电
                TelephonyManager tm = (TelephonyManager) context
                        .getSystemService(Service.TELEPHONY_SERVICE);

                switch (tm.getCallState()) {
                    case TelephonyManager.CALL_STATE_RINGING:
                        incomingFlag = true;// 标识当前是来电
                        incoming_number = intent.getStringExtra("incoming_number");
                        Log.i(TAG, "RINGING : " + incoming_number);
                        inite();
                        break;
                    case TelephonyManager.CALL_STATE_OFFHOOK:
                        if (incomingFlag) {
                            Log.i(TAG, "incoming ACCEPT : " + incoming_number);
                            // inite();
                        }
                        break;
                    case TelephonyManager.CALL_STATE_IDLE:
                        if (incomingFlag) {
                            inite();
                            Log.i(TAG, "incoming IDLE ");
                        }
                        break;
                }
            }
        }
    }
}
